package com.sap.jcp.sm.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.sap.jcp.sm.domain.User;

public class UserDAOImpl implements UserDAO {

	@SessionTarget
	Session session;
	@TransactionTarget
	Transaction transaction;

	@SuppressWarnings("unchecked")
	public List<User> listUser() {
		List<User> users = null;
		try {
			//System.out.println("listUser");
			users = session.createQuery("from User").list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return users;
	}

	public void saveUser(User user) {
		try {
			transaction.begin();
			//System.out.println("saveUser");
			session.save(user);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		}
	}

	public boolean isUserAlreadyExist(String emailId) {
		if(getUser(emailId) != null) {
			return true;
		}
		return false;
	}
	public void updateUser(User user) {
		try {
			transaction.begin();
			//System.out.println("updateUser");
			session.saveOrUpdate(user);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		}
	}

	public void deleteUser(User user) {
		try {
			transaction.begin();
			//System.out.println("deleteUser");
			session.delete(user);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		}
	}

	@Override
	public User loginUser(User user) {
		//System.out.println("loginUser");
		String hql = "from User where emailId = :emailId and password = :password and status = :status";
		Query query = session.createQuery(hql);
		query.setParameter("emailId", user.getEmailId());
		query.setParameter("password", user.getPassword());
		query.setParameter("status", "Approved");
		List<User> loginUser = query.list();
		if (loginUser != null && !loginUser.isEmpty()) {
			return loginUser.get(0);
		}
		return null;
	}


	public User getUser(String emailId) {
		String hql = "from User where emailId = :emailId";
		Query query = session.createQuery(hql);
		query.setParameter("emailId", emailId);
		List<User> loginUser = query.list();
		if (loginUser != null && !loginUser.isEmpty()) {
			return loginUser.get(0);
		}
		return null;
	}

	@Override
	public List<User> pendingListUser(String status) {
		String hql = "from User where status = :status ORDER BY primaryTrack";
		Query query = session.createQuery(hql);
		query.setParameter("status", status);
		List<User> loginUser = query.list();
		return loginUser;
	}

}
